<template>
  <div class="flexContent">
    <h3>退货信息</h3>
    <div class="inner">
      <el-form ref="ruleForm" :disabled="detail.isDetail" :model="sform" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="供应商：" prop="supplierId">
              <el-select @click.native="getSCMList" v-model="sform.supplierId" clearable
                :disabled="formData.tableData.length > 1" placeholder="请选择供应商" style="width: 90%" popper-class="eloption"
                filterable>
                <el-option v-for="item in firstSupplierList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="出库仓库：" prop="warehouseId">
              <el-select @click.native="reqWarehouseList" v-model="sform.warehouseId"
                :disabled="formData.tableData.length > 1" clearable placeholder="请选择出库仓库" style="width: 90%"
                popper-class="eloption" filterable>
                <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="备注：">
              <el-input v-clearEmoji v-model.trim="sform.remake" placeholder="最多输入50个字符" maxlength="50" show-word-limit
                style="width: 90%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="table">
      <el-form ref="formData" :model="formData" @submit.native.prevent>
        <el-table border class="tablebox" :data="formData.tableData" max-height="552" style="width: 100%" size="medium">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="commodityName" label="商品名称" min-width="180">
            <template slot-scope="scope">
              <span v-if="detail.isDetail || scope.row.firstCode">{{
                scope.row.commodityName
              }}</span>
              <el-form-item v-if="!detail.isDetail && !scope.row.firstCode" :prop="'tableData.' + scope.$index + '.name'">
                <el-popover ref="myPopover" v-model="dialogVisible" placement="bottom-start" width="800" trigger="manual"
                  @show="openPopover">
                  <el-table border size="medium" height="300" :data="gridData1" class="tablebox" highlight-current-row
                    @row-click="handleCurrentChanges">
                    <el-table-column align="center" type="index" label="序号" width="80" />
                    <el-table-column align="center" property="name" label="商品" />
                    <el-table-column align="center" property="mnemonic" label="助记符" />
                    <el-table-column align="center" property="standard" label="规格" />
                    <el-table-column align="center" property="unitName" label="单位" />
                    <el-table-column align="center" property="producer" label="产地" />
                  </el-table>
                  <div class="pagination">
                    <el-pagination :current-page="page.pageNum" :page-sizes="$pageSizes" :page-size="page.pageSize"
                      background layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total"
                      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                  </div>
                  <el-input v-clearEmoji slot="reference" ref="inputaldQty" v-model.trim="scope.row.name"
                    placeholder="请输入..." class="group-inp" size="small" style="width: 100%"
                    @keyup.enter.native="getGoodsInfo(scope.row.name)" @input.enter.native="hiddenPop" />
                </el-popover>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="mnemonic" label="助记符" />
          <el-table-column align="center" prop="firstCode" label="商品条码" width="150" /> -->
          <el-table-column align="center" prop="standard" label="规格" />
          <el-table-column align="center" prop="unitName" label="单位" />
          <el-table-column align="center" prop="regionName" label="区域" />
          <el-table-column align="center" prop="positionName" label="仓位" :min-width="120"/>
          
          <el-table-column align="center" prop="inboundCount" label="入库数量" :min-width="100"/>
          <el-table-column align="center" prop="inventoryNum" label="可退数量" :min-width="100"/>
          <el-table-column align="center" prop="agreedPrice" label="协议进价(元)" :min-width="120"/>
          <el-table-column align="center" prop="outboundPiece" label="退货件数" :min-width="120"/>
          <el-table-column align="center" prop="outboundCount" label="退货数量" show-overflow-tooltip min-width="180">
            <template slot-scope="scope">
              <el-form-item v-if="!detail.isDetail && scope.row.firstCode"
                :prop="'tableData.' + scope.$index + '.outboundCount'"
                :rules="tableRules(formData.tableData[scope.$index])">
                <el-input v-clearEmoji ref="inputaldQty" v-model.number.number="scope.row.outboundCount" placeholder=""
                  class="group-inp" size="small" style="width: 100%"
                  @change="numberChange($event, scope.$index, scope.row)" />
              </el-form-item>
              <span v-if="detail.isDetail">{{
                scope.row.outboundCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="returnMoney" label="退货金额" show-overflow-tooltip :min-width="100"/>
          
          <el-table-column align="center" prop="manufactureTime" label="生产日期" :min-width="100">
            <template v-slot="{row}">
              <span>{{ row.manufactureTime | parseTime('YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>
          <!-- && scope.row.firstCode -->
          <el-table-column align="center" prop="batchNumber" label="批次号" :min-width="180"/>
          <el-table-column align="center" prop="bigPacking" label="大包装" />
          <el-table-column v-if="!detail.isDetail" align="center" label="操作">
            <template v-if="!detail.isDetail && scope.row.firstCode" slot-scope="scope">
              <el-button type="text" style="color: red"
                @click="delRegionByIndex(scope.$index, scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" v-if="!detail.isDetail" @click="cancelBtn">取消</el-button>
      <el-button class="celBtn" v-if="detail.isDetail" @click="cancelBtn">返回</el-button>
      <el-button class="addBtn" v-if="!detail.isDetail" @click="submitData('formData')">确定</el-button>
    </div>
    <goodsDialog ref="goodsDialogRef" :show-dialog.sync="showDialog" :grid-data2="gridData2" @commitFn="commitFn" />
  </div>
</template>

<script>
import GoodsDialog from "./components/goodsDialog";
import {
  reqWarehouseList,
  addBuyReturns,
  fuzzySearchGoods,
  getOrderByGoodsSupplier,
  getBuyReturnsRecordDetail,
} from "@/api/warehouse";
import { DecimalUtils } from "@/utils/math";
import { getSCMList } from "@/api/scm";
import { parseTime } from "@/utils";
export default {
  name: "PurchaseBackAdd",
  components: {
    GoodsDialog,
  },
  watch: {
    formData: {
      handler(newVal, oldVal) {
        this.page = {
          pageNum: 1,
          pageSize: 20,
          total: 0,
        };
        console.log(this.page);
      },
      deep: true,
    },
  },
  data() {
    return {
      dialogTableVisible: false,
      dialogVisible: false,
      firstSupplierList: [],
      warehouseList: [],
      sform: {
        supplierId: "",
        remake: "", // 备注
        warehouseId: "",
        detailsList: [],
      },
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      rules: {
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
        warehouseId: [
          { required: true, message: "请选择出库仓库", trigger: "blur" },
        ],
      },
      formData: {
        buyRemake: "",
        warehouseName: "",
        warehouseId: "",
        tableData: [{ name: "" }],
      },
      gridData1: [],
      gridData2: [],
      selected: {},
      radio: "",
      detail: {
        isDetail: false,
        id: "",
      },
      showDialog: false,
      goodsName: "",
    };
  },
  created() {
    this.getSCMList();
    this.reqWarehouseList();
    this.detail.id = this.$route.query.id;
    this.detail.isDetail = !!this.$route.query.id;
    if (this.detail.isDetail) {
      // 获取详情
      this.getBuyReturnsRecordDetail();
    }
  },
  methods: {
    async getBuyReturnsRecordDetail() {
      // console.log(this.detail.id, 'id')
      const res = await getBuyReturnsRecordDetail({ id: this.detail.id });
      if (res.code === 200) {
        console.log(res.data, "详情");
        this.sform.supplierId = res.data.supplierId;
        this.sform.warehouseId = res.data.warehouseId;
        this.sform.remake = res.data.remake;
        this.formData.tableData = res.data.detailsList;
      }
      console.log(res);
    },
    async getSCMList() {
      const res = await getSCMList();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data.list;
      }
    },
    async reqWarehouseList() {
      const res = await reqWarehouseList();
      if (res.code === 200) {
        this.warehouseList = res.data;
        // console.log(this.warehouseList, 'Ware')
      }
    },
    submitData(formName) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.formData.tableData.length <= 1)
            return this.$message.warning("请先选择退货订单");
          this.$refs.formData.validate(async (valid) => {
            if (valid) {
              console.log(this.formData, "formData");
              this.sform.detailsList = [];
              this.formData.tableData.forEach((item) => {
                if (item.id && item.outboundCount) {
                  this.sform.detailsList.push({
                    commodityPositionId: item.id,
                    returnMoney: item.returnMoney,
                    outboundCount: item.outboundCount,
                    // outboundPiece: item.outboundPiece * 1,
                  });
                }
              });
              console.log(this.sform, "this.sform");
              // return
              const res = await addBuyReturns({
                supplierId: this.sform.supplierId,
                warehouseId: this.sform.warehouseId,
                remake: this.sform.remake,
                detailsList: this.sform.detailsList,
              });
              if (res.code === 200) {
                this.$message.success("添加成功");
                this.closeTag("receiving");
              } else {
                // this.$message.error(res.message);
              }
            }
          });
        }
      });
    },
    delRegionByIndex(index, id) {
      this.formData.tableData.splice(index, 1);
      this.selected = {};
      this.radio = "";
      this.$refs.goodsDialogRef.deleteFn(index, id);
    },
    // delDiasByIndex(index) {},
    numberChange(e, index, row) {
      console.log(row, "row");
      // 判断
      // 修改退货金额
      const sum = DecimalUtils.multiply(row.agreedPrice, row.outboundCount);
      this.$set(this.formData.tableData[index], "returnMoney", sum);
      // 退货件数
      const sum2 = DecimalUtils.subNumber(
        DecimalUtils.divide(row.outboundCount, row.bigPacking),
        2
      );
      this.$set(this.formData.tableData[index], "outboundPiece", sum2);
    },
    // 表单验证
    tableRules(row, scope) {
      // console.log(scope);
      return [
        { required: true, message: "退货数量不能为空" },
        // { type: "number", message: "退货数量必须为正整数" },
        {
          pattern: /^\+?[1-9]\d*$/,
          message: "退货数量必须为正整数",
          trigger: "blur",
        },
        // {
        //   validator: (rule, value, callback) => {
        //     if (value % row.bigPacking != 0) {
        //       callback("退货数量须为大包装的倍数");
        //     } else {
        //       callback();
        //     }
        //   },
        // },
        {
          validator: (rule, value, callback) => {
            if (value > row.inventoryNum) {
              callback("退货数量不能超过可退数量");
            } else {
              callback();
            }
          },
        },
      ];
    },
    async getGoodsInfo(name) {
      console.log("222");
      // 校验仓库为必填
      if (name) {
        this.goodsName = name;
      }
      // 调接口，搜索列表
      if (this.goodsName === "")
        return this.$message.warning("请输入要搜索的内容");
      const res = await fuzzySearchGoods({
        name: this.goodsName,
        ...this.page,
      });
      if (res.code === 200) {
        this.gridData1 = res.data.list;
        this.page.pageNum = res.data.pageNum;
        this.page.pageSize = res.data.pageSize;
        this.page.total = res.data.total;
        console.log(res.data, "res.data");
        console.log(this.gridData1, "this.gridData1");
        // 1. 列表无数据，提示
        if (this.gridData1.length === 0) {
          this.$message.warning("未找到该商品");
          console.log("未找到该商品");
          return;
        } else {
          this.dialogVisible = true;
          // 2. 列表有数据，弹窗展示列表
          console.log(this.gridData1, "有商品");
        }
      }
    },
    cancelBtn() {
      this.closeTag("purchaseBack");
    },
    hiddenPop() {
      this.dialogVisible = false;
    },
    async handleCurrentChanges(val) {
      // console.log(val, '表格高亮')
      this.$refs.ruleForm.validate(async (isOk) => {
        if (isOk) {
          console.log(isOk, "ok");
          // 调接口
          if (val) {
            const res = await getOrderByGoodsSupplier({
              commodityId: val.id,
              warehouseId: this.sform.warehouseId,
              supplierId: this.sform.supplierId,
            });
            if (res.code === 200) {
              // 1.有数据，打开弹窗
              // 1.1 判断数据是否为0
              this.gridData2 = res.data;
              if (this.gridData2.length === 0) {
                this.$message.warning("未找到该商品入库记录");
                // 关闭popover
                return;
              }
              this.dialogVisible = false;
              this.dialogVisible = false;
              console.log(res.data, "res.data");
              this.showDialog = true;
            } else {
              // 2.没有数据，提示
              // this.$message.warning('未找到该商品相关订单')
            }
          }
        } else {
          this.$message.warning("请先选择仓库和供应商");
        }
      });
    },
    commitFn(list) {
      console.log(list, "回显");
      this.formData.tableData = list;
      this.formData.tableData.push({ name: "" });
    },
    openPopover() {
      // 弹框展示时注册全局点击事件
      if (this.dialogVisible) {
        document.addEventListener("click", this.hidePopover, false);
      } else {
        document.removeEventListener("click", this.hidePopover, false);
      }
    },
    hidePopover(e) {
      // 全局点击事件，检测当前点击位置不包含弹框的元素，则隐藏弹框
      if (this.dialogVisible) {
        if (!this.$refs.myPopover?.$el.contains(e.target)) {
          this.dialogVisible = false;
        }
      } else {
        document.removeEventListener("click", this.hidePopover, false);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getGoodsInfo(this.goodsName);
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getGoodsInfo(this.goodsName);
    },
  },
};
</script>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }
}
</style>
